﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Htx.SignalR.WebApp.Hubs
{
    public class ChatHub : Hub
    {
        private static List<OnLineClient> conns = new List<OnLineClient>();     // 保存连接的用户

        /// <summary>
        /// 客户端连接
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            var name = this.Context.GetHttpContext().Request.Query["name"];

            var connectId = this.Context.ConnectionId;

            var client = new OnLineClient { Id = connectId, Name = name };

            conns.Add(client);

            return base.OnConnectedAsync();
        }

        /// <summary>
        /// 客户端断开连接
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception exception)
        {
            var conn = conns.FirstOrDefault(a => a.Id == this.Context.ConnectionId);

            if (conn != null)
            {
                conns.Remove(conn);
            }

            return base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 接收到消息后想客户端推送
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessage(string name, string message)
        {
            if (string.IsNullOrEmpty(name))
            {
                // 广播消息
                name = conns.FirstOrDefault(a => a.Id == this.Context.ConnectionId).Name;
                await Clients.All.SendAsync("ReceiveMessage", name, message);
                return;
            }
            // 指定用户消息
            var host = conns.FirstOrDefault(a => a.Id == this.Context.ConnectionId);
            var sendName = conns.FirstOrDefault(a => a.Id == this.Context.ConnectionId).Name;
            var clientArr = conns.Where(a => a.Name == name).ToList();
            if (clientArr.Count == 0) return;
            await this.Clients.Clients(clientArr.Select(a => a.Id)).SendAsync("ReceiveMessage", sendName, $"[私密消息]{message}");
        }

    }

    public class OnLineClient
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}
